const h = (tag,props,children) => {
  return {
    tag,
    props,
    children
  }
}


const mount = (vnode,container) => {
  // 1.处理tag
  const el =vnode.el = document.createElement(vnode.tag);
  // 2.处理props
  for(const key in vnode.props){
    const value = vnode.props[key];
    // 处理事件
    if(key.startsWith('on')){
      el.addEventListener(key.slice(2).toLowerCase(),value)
    }else{
      el.setAttribute(key,value)
    }
  }
  // 3.处理children
  if (vnode.children) {
    if (typeof vnode.children === 'string') {
      el.textContent = vnode.children
    }else{
      vnode.children.forEach(item => {
        mount(item,el)
      });
    }
  }
  container.appendChild(el)
}


const patch = function (oldVNode,newVNode){
  // 1.对比tag
  if(oldVNode.tag !== newVNode.tag){
    const oldVNodeElParent = oldVNode.el.parentElement;
    oldVNodeElParent.removeChild(oldVNode);
    mount(newVNode,oldVNodeElParent)
  }else{
    // 2.对比props
    const el = newVNode.el = oldVNode.el;
    const oldProps = oldVNode.props || {};
    const newProps = newVNode.props || {};
    // 2.1.新对象有，就对象没有
    for(const key in newProps){
      if(newProps[key] !== oldProps[key]){
        el.setAttribute(key,newProps[key])
      }
    }
    // 2.2.新对象没有，旧对象有
    for(const key in oldProps){
      if(!newProps[key]){
        el.removeAttribute(key)
      }
    }



    // 3.对比children

    const oldChildren = oldVNode.children || []
    const newChildren = newVNode.children || []

    // 3.1如果新的children是字符串
    if(typeof newChildren === 'string'){
      if(typeof oldChildren === 'string'){
        el.textContent = newChildren
      }else{
        el.innerHTML = newChildren
      }
    // 3.2如果新的children是数组
    }else{
      if (typeof oldChildren === 'string') {
        el.innerHTML = ''
        newChildren.forEach(item=>mount(item,el))
      }else{
        const commonLength = Math.min(oldChildren.length,newChildren.length)
        // 数组长度相同比较
        for(let i =0;i<commonLength;i++){
          patch(oldChildren[i],newChildren[i])
        }
        // 旧数组比较长
        if(oldChildren.length >newChildren.length){
          oldChildren.slice(commonLength).forEach(item=>{
            el.removeChild(item.el)
          })
        }
        // 新数组比较长
        if(newChildren.length >oldChildren.length){
          newChildren.slice(commonLength).forEach(item=>{
            mount(item,el)
          })
        }
      }
    }






  }
}